/**
 * Created by shenhai on 15/9/14.
 */



var UserService = require('../../../services/mis/appuser/appUserService');
var messageUtil = require('../../../common/utils/messageUtil');
var toolUtil = require('../../../common/utils/toolUtil');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var moment = require('moment');
var userInvitation = mongoose.model('user_invitation');
var nodeExcel = require('excel-export');

exports.getCancelReasonMessageList=function(req, res)
{
    UserService.getCancelReasonMessageListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when frontUserList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when frontUserList...'));
        }else {
            // alert(results);

            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }

    });
};

/* 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start */
// 获取创始人申请拒绝理由信息
exports.getDeclineReasonMessageList=function(req, res) {
    UserService.getDeclineReasonMessageListService(req, function(err, results) {
        if (err) {
            logger.error('Exception happen when getDeclineReasonMessageListService...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when getDeclineReasonMessageListService...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};
/* 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end */

exports.frontUserList = function(req, res) {

    UserService.frontUserListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when frontUserList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when frontUserList...'));
        }else {
           // alert(results);
            var data = {
                count:results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};

// 修改用户资料
exports.updateInfo = function(req, res) {

    UserService.updateInfoService(req, function(err, results) {

        if (err) {



            <!--  宝宝树66小区二次改造    mod   gct  20170817   start   -->
            /*logger.error('Exception happen when updateInfo...' + err.message);
             res.json(messageUtil.composeFailedMessage(req, 'Exception happen when updateInfo...'));*/
            if(err.status==999)
            {
                res.json(messageUtil.composeSucceededMessage(req, null,err));
            }
            else
            {
                logger.error('Exception happen when updateInfo...' + err.message);
                res.json(messageUtil.composeFailedMessage(req, 'Exception happen when updateInfo...'));
            }
            <!--  宝宝树66小区二次改造    mod   gct  20170817   end   -->
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.updateParents = function(req, res) {

    UserService.updateParentsService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when updateParents...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when updateParents...'));
        }else {

            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.isModerator = function(req, res) {

    UserService.isModeratorService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when isModerator...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when isModerator...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

// 拉黑/取消拉黑
exports.pullBlack = function(req, res) {

    UserService.pullBlackService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when pullBlack...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when pullBlack...'));
        }else {

            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};


/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   start   */
// 禁言/取消禁言
exports.speakNotAllow = function(req, res) {

    UserService.speakNotAllowService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when speakNotAllow...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when speakNotAllow...'));
        }else {

            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   end   */

/*  宝宝树66小区三期改造  删除用户  add   luolh  20170929   start   */
// 删除用户/复活用户
exports.appUserDelete = function(req, res) {

    UserService.appUserDeleteService(req, function(err, results) {
        if (err) {
            logger.error('Exception happen when appUserDelete...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};
/*  宝宝树66小区三期改造  删除用户  add   luolh  20170929   end   */

// 升级达人/取消达人
exports.talent = function(req, res) {

    var body = req.body;

    if (!body.userID) {
        return res.json(messageUtil.composeFailedMessage(req, 'body参数错误 when modifyVAuthStatus...'));
    }

    var userID = body.userID;

    UserService.talentService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when set/cancel talent...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when set/cancel talent...'));
        }else {
            toolUtil.setUserByToken(userID);

            if (body.talent) {
                var arg = {
                    userId: userID,
                    userRole: 1,
                    userActionType: 2
                };

                arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

                scoreProxy.invoke('addScore', [arg], function (err, reply) {
                    try {
                        var data = JSON.parse(decodeURIComponent(reply));
                        logger.info(data);
                    } catch (e) {
                        logger.error('hessianInvokeAddScore---' + e);
                        logger.info(reply);
                    }
                });
            }

            logger.debug("Successfully to set/cancel user as talent...!");
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });


};

// 升级V / 取消V
exports.modifyVAuthStatus = function(req, res) {

    var body = req.body;

    if (!body.userID) {
        return res.json(messageUtil.composeFailedMessage(req, 'body参数错误 when modifyVAuthStatus...'));
    }

    var userID = body.userID;

    UserService.modifyVAuthStatusService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when modifyVAuthStatus...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when modifyVAuthStatus...'));
        }else {


            //toolUtil.setUserByToken(userID);
            //
            //var status = body.authenticationStatus ? 1 : 0;
            //
            ////个推
            //var content = {
            //    f: 3,
            //    vStatus: status
            //};
            //var pushData = {
            //    uList: [userID],
            //    content: content
            //};
            //toolUtil.putMessageTransmissionPushMQ(pushData);
            //
            //if (body.authenticationStatus) {
            //    var arg = {
            //        userId: userID,
            //        userRole: 1,
            //        userActionType: 1
            //    };
            //
            //    arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
            //
            //    scoreProxy.invoke('addScore', [arg], function (err, reply) {
            //        try {
            //            var data = JSON.parse(decodeURIComponent(reply));
            //            logger.info(data);
            //        } catch (e) {
            //            logger.error('hessianInvokeAddScore---' + e);
            //            logger.info(reply);
            //        }
            //    });
            //
            //    if (results[2] != null) {
            //        mysqlUtil.generateUserVoucher(results[2], 2, userID, function (err, voucher) {
            //            if (err) {
            //                logger.error(err.message);
            //            } else {
            //                userInvitation.update({invitee: userID}, {
            //                    score: voucher.value,
            //                    dateLastModified: new Date(),
            //                    type: voucher.type
            //                }).exec();
            //
            //                //放入周排行榜
            //                var key = 'rank:invitation:' + moment().startOf('isoWeek').format('YYYYMMDD');
            //                redisClient.ZINCRBY(key, 1, results[2]);
            //
            //                //放入总排行榜
            //                var totalKey = 'rank:invitation:total';
            //                redisClient.ZINCRBY(totalKey, 1, results[2]);
            //            }
            //        });
            //
            //        //TODO 邀请通知
            //
            //        var message = {
            //            msgType: 'invite',
            //            userId: result[2],
            //            inviteUserId: userID
            //        };
            //        toolUtil.putMessageBusinessMQ(message);
            //
            //        //建立相互关注
            //        UserService.eachOtherFollowupService(userID + '', results[2] + '');
            //    }
            //}


            logger.debug("Successfully to set/cancel User As VUser... ! ");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }

    });
};


//
exports.modifyUserRole = function(req, res) {

    var body = req.body;

    if (!body.userID) {
        return res.json(messageUtil.composeFailedMessage(req, 'body参数错误 when modifyUserRole...'));
    }

    var userID = body.userID;

    UserService.modifyUserRoleService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when modifyUserRole...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when modifyVAuthStatus...'));
        }else {

            logger.debug("Successfully to modifyUserRole... ! ");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }

    });
};


exports.rejectRole = function(req, res) {

    UserService.rejectRoleService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when rejectRole...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when rejectRole...'));
        }else {

            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};


exports.exportUser = function (req, res) {

    //var input = req.cparams;
    //logger.debug(input);
    //var page = req.params.page;
    //var size = req.params.size;

    UserService.exportUserService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when exportUser...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when exporUser...'));
        } else {

            if(!results[1]) {
                logger.error('Exception happen when exporUserScore...导出数据为0' + err.message);
                res.json(messageUtil.composeSucceededMessage(req, null, {}));
            }else {
                var conf = {};

                conf.cols = [{
                    caption: '用户ID',
                    type: 'string'
                }, {
                    caption: '手机号码',
                    type: 'string'
                },
                {
                    caption: '昵称',
                    type: 'string'
                },
                {
                    caption: '来源',
                    type: 'string'
                },
                {
                    caption: '性别',
                    type: 'string'
                },
                {
                    caption: '小区',
                    type: 'string'
                },
                {
                    caption: '详细地址',
                    type: 'string'
                }, {
                    caption: 'V用户',
                    type: 'string'
                },{
                    caption: '角色',
                    type: 'string'
                },
                {
                    caption: '创建时间',
                    type: 'string'
                }];
                //logger.debug(results[1]);
                var data = results[1];
                var tempRows = [];
                logger.debug(data.length);
                for (var i = 0; i < data.length; i++) {
                    var temp = [];


                    temp.push(data[i]._id.toString());
                    if (data[i].mobilePhone) {
                        temp.push(data[i].mobilePhone)
                    } else {
                        temp.push("");
                    }
                    if (data[i].nickName) {
                        temp.push(data[i].nickName)
                    } else {
                        temp.push("");
                    }
                    if (data[i].regChannelId) {
                        temp.push(data[i].regChannelId)
                    } else {
                        temp.push("");
                    }
                    if (data[i].gender) {
                        temp.push(data[i].gender)
                    } else {
                        temp.push("");
                    }
                    if (data[i].community) {
                        temp.push(data[i].community.communityName)
                    } else {
                        temp.push("");
                    }
                    if (data[i].community) {
                        temp.push(data[i].community.communityAddress)
                    } else {
                        temp.push("");
                    }
                    if(data[i].authenticationStatus) {
                        temp.push(data[i].authenticationStatus == false ? '否' : '是');
                    }else{
                        temp.push('否');
                    }
                    if(data[i].userRole){
                        var role='';
                        for(r in data[i].userRole){
                            if(data[i].userRole[r]==1)role +='版主 ';
                            if(data[i].userRole[r]==3)role +='雷锋团';
                        }
                        temp.push(role);

                    }else{
                        temp.push("");
                    }
                    if (data[i].dateCreated != null) {
                        var dateCreated = new Date(data[i].dateCreated);
                        temp.push(dateCreated.getFullYear() + "-" + (dateCreated.getMonth() + 1) + "-" + dateCreated.getDate() + " " + dateCreated.getHours() + ":" + dateCreated.getMinutes());
                    } else {
                        temp.push("");
                    }
                    //temp.push(data[i].presentPrice);
                    ////logger.debug(data[i].presentPrice);
                    //if(data[i].dealStatus) {
                    //    temp.push(data[i].dealStatus == 0 ? '未交易' : '已交易');
                    //}else{
                    //    temp.push('未交易');
                    //}
                    ////logger.debug(data[i].dealStatus);

                    tempRows.push(temp);

                    //logger.debug(tempRows);
                }
                conf.rows = tempRows;

                var ret = nodeExcel.execute(conf);
                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
                res.end(ret, 'binary');
            }
        }
    });


};